'''
 * CaRComp Execution Environment
 * 
 * Copyright (C) 2011 Taylor L. Riche
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.


Graciously stolen from Dive Into Python:
http://diveintopython.org/functional_programming/all_together.html

Modified to work with Python 3 conventions

'''
import unittest, os, re, sys

def mod_to_path(mod_name):
    '''Given a mod name in . notation return a proper path with /'''
    return mod_name.replace('.', '/')

def regression_test():
    '''
    Runs all tests in a given sub module. If no argument given, runs tests
    in the current directory.
    '''   
    path = os.path.abspath(os.path.dirname(sys.argv[0]))
    index = 1
    if len(sys.argv) > 1:
        if sys.argv[1] == '-v':
            index = 2
    if len(sys.argv) > 1:
        path = path + '/' + mod_to_path(sys.argv[index])
    try:
        files = os.listdir(path)
    except OSError as err:
        print(err)
        quit()
    test = re.compile("_test\.py$", re.IGNORECASE)      
    files = [file for file in files if test.search(file)]
    filenameToModuleName = lambda f: os.path.splitext(f)[0]
    if len(sys.argv) > 1:
        moduleNames = ['ft.tests.{}.{}'.format(sys.argv[index],filenameToModuleName(file)) for file in files]
    else: 
        moduleNames = ['ft.tests.{}'.format(filenameToModuleName(file)) for file in files]
    for mod_name in moduleNames:
        __import__(mod_name)   
    modules = [sys.modules[mod_name] for mod_name in moduleNames]
    #print(modules)                 
    load = unittest.defaultTestLoader.loadTestsFromModule
    return unittest.TestSuite([load(module) for module in modules])   

if __name__ == "__main__":
    if len(sys.argv) > 1:
        if sys.argv[1] == '-v':
            unittest.main(defaultTest='regression_test', argv=sys.argv[0:2])
    unittest.main(defaultTest='regression_test', argv=[sys.argv[0]])